import * as API_Members from '../../../../api/members'
import * as API_Promotions from '../../../../api/promotions'
import { Foundation } from '../../../../ui-utils/index.js'
Component({
  properties: {
    shopId: String
  },
  data: {
    coupons: '',
  },
  lifetimes: {
    ready() {
      if (this.data.shopId) {
        // 获取店铺优惠券
        API_Promotions.getShopCoupons(this.data.shopId).then(response => {
          response.forEach(key => {
            key.start_time = Foundation.unixToDate(key.start_time, 'yyyy-MM-dd')
            key.end_time = Foundation.unixToDate(key.end_time, 'yyyy-MM-dd')
          })
          this.setData({ coupons: response })
        })
      }
    }
  },
  observers: {
    shopId() {
      if (this.data.shopId) {
        // 获取店铺优惠券
        API_Promotions.getShopCoupons(this.data.shopId).then(response => {
          response.forEach(key => {
            key.start_time = Foundation.unixToDate(key.start_time, 'yyyy-MM-dd')
            key.end_time = Foundation.unixToDate(key.end_time, 'yyyy-MM-dd')
          })
          this.setData({ coupons: response })
        })
      }
    }
  },
  methods: {
    /** 显示弹窗 */
    popup() {
      this.selectComponent('#bottomFrame').showFrame();
    },
    // 领取店铺优惠券
    handleReceiveCoupon(e) {
      const coupon = e.target.dataset.coupon
      if (!wx.getStorageSync('refresh_token')) {
        wx.showToast({ title: '您还未登录!', image: 'https://localhost/images/icon_error.png' })
        return false
      }
      API_Members.receiveCoupons(coupon.coupon_id).then(() => {
        wx.showToast({ title: '领取成功' })
      })
    }
  }
})
